package com.yubest.thymeleaf.controller;

import com.yubest.thymeleaf.bean.Product;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 示例-控制器
 *
 * @Author: hweiyu
 * @Date: 2022/11/14 16:18
 */
@Controller
public class HelloController {

    @GetMapping(value = "/")
    public String index(Model model) {
        model.addAttribute("title", "Spring Boot + Thymeleaf 示例");

        Product product = new Product();
        product.setDescription("花生油");
        product.setPrice(169);
        product.setAvailableFrom(new Date());
        model.addAttribute("product", product);

        String html =  "Welcome to <b>Thymeleaf</b> world!";
        model.addAttribute("html", html);

        List<Product> products = new ArrayList<>();
        products.add(new Product("花生油", 125, new Date(), "CG"));
        products.add(new Product("苏打饼干", 15, new Date(), "PT"));
        products.add(new Product("拿铁", 45, new Date(), "CX"));
        products.add(new Product("调和油", 20, new Date(), "CX"));
        products.add(new Product("大豆油", 49, new Date(), ""));
        products.add(new Product("玉米汁", 80, new Date(), ""));
        model.addAttribute("products", products);

        return "index";
    }

    @GetMapping(value = "/toAdd")
    public String toAdd(Model model) {
        Product product = new Product("花生油", 119, new Date(), "CX");
        model.addAttribute("product", product);

        return "add";
    }

    @PostMapping(value = "/add")
    public String add(Model model, Product product) {
        model.addAttribute("product", product);
        model.addAttribute("msg", "添加成功");
        return "add";
    }
}
